package com.example.vertification.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.vertification.entity.*;
import com.example.vertification.service.PageService;
import com.example.vertification.service.UserService;
import com.example.vertification.service.UserStationService;
import com.example.vertification.service.UserWithPageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Date;

@RestController
@Api(value = "企业站点接口", tags = "企业站点接口")
public class UserStationController {

    private final UserService userService;
    private final UserStationService userStationService;


    @Autowired
    public UserStationController(UserService userService, UserStationService userStationService) {
        this.userService = userService;
        this.userStationService = userStationService;
    }



    @PostMapping("/set_stations")
    @ApiOperation(value = "传入你的所有站点列表(JSONArray),每个JSONObject需要有(id,lat,lng,name,address)")
    public ResponseEntity<?> set_stations(@RequestBody String body) throws IOException {
        JSONObject get_obj = JSONUtil.parseObj(body);
        User u = userService.getUserByToken(get_obj.getStr("token"));
        if(u==null){
            return ResponseEntity.ok("请先登入!");
        }
        JSONArray jsarr = JSONUtil.parseArray(get_obj.getStr("jsonArray"));
        UserStation us = new UserStation();

        if(userStationService.getEntityByUid(u.getUid()) !=null ){
            us = userStationService.getEntityByUid(u.getUid());
        }

        us.setUid(u.getUid());
        us.setStations(JSONUtil.toJsonStr(jsarr));
        userStationService.save(us);
        return ResponseEntity.ok("success");
    }


    @GetMapping("/get_stations")
    @ApiOperation(value = "传入你的token,获取一组JSONArray,单个JSONObject的属性有(id,lat,lng,name,address")
    public ResponseEntity<?> get_stations(@RequestParam String token) throws IOException {
        User u = userService.getUserByToken(token);
        if(u==null){
            return ResponseEntity.ok("请先登入!");
        }
        UserStation us = userStationService.getEntityByUid(u.getUid());
        if(us==null){
            us = new UserStation();
        }
        String str = us.getStations();
        if(str==null||str.trim().equalsIgnoreCase("")){
            return ResponseEntity.ok(new JSONArray());
        }else{
            JSONArray ja = JSONUtil.parseArray(str);
            return ResponseEntity.ok(ja);
        }

    }




}
